import axios from 'axios';
import {ElMessage, ElNotification} from 'element-plus';
import sysConfig from "@/config";
import tool from '@/utils/tool';
import i18n from "@/locales";
import router from "@/router";
//import router from '@/router';

axios.defaults.baseURL = ''

axios.defaults.timeout = sysConfig.TIMEOUT

// HTTP request 拦截器
axios.interceptors.request.use(
    (config) => {
        let token = tool.cookie.get("TOKEN");
        if (token) {
            config.headers[sysConfig.TOKEN_NAME] = sysConfig.TOKEN_PREFIX + token
        }
        if (!sysConfig.REQUEST_CACHE && config.method == 'get') {
            config.params = config.params || {};
            config.params['_'] = new Date().getTime();
        }
        Object.assign(config.headers, sysConfig.HEADERS)
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

//FIX 多个API同时401时疯狂弹窗BUG
//let MessageBox_401_show = false

// HTTP response 拦截器
axios.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        return Promise.reject(error);
    }
);

var http = {
    globalPromise: function (method, url, params, isJson, config) {
        return new Promise((resolve) => {

            let data;
            if (Array.isArray(params)) {
                data = params;
            }else if(params instanceof FormData){
                config.headers = {"Content-Type": "multipart/form-data"};
                data = params;
            } else {
				if(method==='post'&&typeof(params)==='object'){
					data = tool.objCopy(params);
					tool.deleteTempProps(data);//提交之前去除临时属性
                    let userInfo = tool.data.get("USER_INFO");
                    if (userInfo) {
                        data['userLevelCode'] = userInfo.levelCode;
                        data['loginUserId'] = userInfo.id;
                    }
                    let userDept = tool.data.get("USER_DEPT");
                    if (userDept) {
                        data['loginUserDeptLevelCode'] = userDept.levelCode;
                        data['loginUserDeptId'] = userDept.id;
                    }
                    let currentRole = tool.data.get("CURRENT_ROLE");
                    if (currentRole) {
                        data['roleLevelCode'] = currentRole.levelCode;
                        data['roleId'] = currentRole.id;
                    }

				}
            }
            //国际化服务器端设置
			if(!config.headers){
				config.headers = sysConfig.HEADERS;
			}
			config.headers['Accept-Language']=tool.data.get("APP_LANG")||sysConfig.LANG;

            let req;
            if (isJson) {
                req = axios({method: method, url: url, data: data, ...config});
            } else {
                req = axios({method: method, url: url, params: data, ...config});
            }
            req.then((response) => {
                //公司框架的处理
                if (response.data.fail) {
                    http.isNeedReLogin(response.data);
                }
                resolve(response.data);
            }).catch((error) => {
                //公司框架的处理
				if(error.response){
					if (error.response.data&&error.response.data.fail) {
						http.isNeedReLogin(error.response.data);
						resolve(error.response.data);
					} else {
						let notifyCtrKey = "ERROR_STATUS_NOTIFIED_"+error.response.status;
						let hasNotify  = tool.data.get(notifyCtrKey);
						//优化token失效后多个请求同时弹出失效提示的问题
						if(!hasNotify){
							ElNotification.error({
								title: i18n.global.tc("common.notify_error_title"),
								message: i18n.global.tc("common.notify_error_msg") + error.response.status,
							});
							tool.data.set(notifyCtrKey,true,2)
						}
						resolve({});
						// reject(error);
					}
				}else{
					let errorKey = error+'';
					errorKey = errorKey.replaceAll(' ','');
					let notifyCtrKey = "ERROR_STATUS_NOTIFIED_"+errorKey;
					let hasNotify  = tool.data.get(notifyCtrKey);
					//优化token失效后多个请求同时弹出失效提示的问题
					if(!hasNotify){
						ElMessage.error(error);
						tool.data.set(notifyCtrKey,true,2)
					}
					resolve({});
				}
            })
        })
    },
    isNeedReLogin: function (data) {
        if (data && data.code) {
            let code = data.code;
            let notifyCtrKey = "ERROR_CODE_NOTIFIED_"+code;
            let hasNotify  = tool.data.get(notifyCtrKey);
            //优化token失效后多个请求同时弹出失效提示的问题
            if(!hasNotify){
                let key = "code." + code;
                let localMsg = i18n.global.tc(key);
                ElNotification.error({
                    title: i18n.global.tc("common.notify_error_title"),
                    message: localMsg === key ? data.msg : localMsg,
                });
                tool.data.set(notifyCtrKey,true,2)
                if (code === 5001 || code === 5002
                    || code === 5003 || code === 5004) {
                    router.replace({
                        path: '/login'
                    });
                }
            }
        }
    },
    /** get 请求
     * @param  {string} url 接口地址
     * @param  {object} params 请求参数
     * @param  {object} config 参数
     */
    get: function (url, params = {}, config = {}) {
        return this.globalPromise('get', url, params, false, config);
    },

    /** post 请求
     * @param  {string} url 接口地址
     * @param  {object} data 请求参数
     * @param  {object} config 参数
     */
    post: function (url, data = {}, config = {}) {
        return this.globalPromise('post', url, data, true, config);
    },
    /** post 请求
     * @param  {string} url 接口地址
     * @param  {object} data 请求参数
     * @param  {object} config 参数
     */
    post2: function (url, data = {}, config = {}) {
        return this.globalPromise('post', url, data, false, config);
    },

    /** put 请求
     * @param  {string} url 接口地址
     * @param  {object} data 请求参数
     * @param  {object} config 参数
     */
    put: function (url, data = {}, config = {}) {
        return this.globalPromise('put', url, data, true, config);
    },

    /** patch 请求
     * @param  {string} url 接口地址
     * @param  {object} data 请求参数
     * @param  {object} config 参数
     */
    patch: function (url, data = {}, config = {}) {
        return this.globalPromise('patch', url, data, true, config);
    },

    /** delete 请求
     * @param  {string} url 接口地址
     * @param  {object} data 请求参数
     * @param  {object} config 参数
     */
    delete: function (url, data = {}, config = {}) {
        return this.globalPromise('delete', url, data, true, config);
    },

    /** jsonp 请求
     * @param  {string} url 接口地址
     * @param  {string} name JSONP回调函数名称
     */
    jsonp: function (url, name = 'jsonp') {
        return new Promise((resolve) => {
            var script = document.createElement('script')
            var _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
            script.id = _id
            script.type = 'text/javascript'
            script.src = url
            window[name] = (response) => {
                resolve(response)
                document.getElementsByTagName('head')[0].removeChild(script)
                try {
                    delete window[name];
                } catch (e) {
                    window[name] = undefined;
                }
            }
            document.getElementsByTagName('head')[0].appendChild(script)
        })
    }
}

export default http;
